//
//  ZZNewsChannelCollectionView.m
//  ZZNews
//
//  Created by 周英培 on 16/7/27.
//  Copyright © 2016年 周英培. All rights reserved.
//

#define KZZNewsChannelCell @"KZZNewsChannelCell"

#import "ZZNewsChannelCollectionView.h"
#import "ZZNewsChannelCollectionViewCell.h"
#import "ZZNewsChannelModel.h"
@interface ZZNewsChannelCollectionView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (nonatomic,strong) NSMutableArray *channels;

@end

@implementation ZZNewsChannelCollectionView

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    
    self = [super initWithFrame:frame collectionViewLayout:layout];
    
    if (self) {
        
        //MARK:注册通知，接收新闻主界面滚动后的位置，使新闻频道栏滚动对应的位置
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMainNewsIndexPathWithNotify:) name:@"MainNewsIndexPath" object:nil];
        
        self.backgroundColor = [UIColor greenColor];
        
        self.dataSource = self;
        
        self.delegate = self;
        
        self.bounces = NO;
        
        self.showsVerticalScrollIndicator = NO;
        
        self.showsHorizontalScrollIndicator = NO;
        
        //MARK:新闻频道栏Ui界面搭建完成，开始加载网络数据
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [self loadServiceDataWithUrlString:@"http://127.0.0.1/topic_news.json" completionBlock:^{
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
                
                [self selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
                
                //MARK:发送通知，发送新闻频道栏的数据给新闻主界面
                [[NSNotificationCenter defaultCenter] postNotificationName:@"NewsChannelData" object:self.channels];
                
            }];
    
            
        });
        
        //MARK:注册cell
        [self registerClass:[ZZNewsChannelCollectionViewCell class] forCellWithReuseIdentifier:KZZNewsChannelCell];
        
    }
    
    return self;

}

/// 注册通知的接收方法，接收新闻主界面滚动后的位置，使新闻频道栏滚动对应的位置
- (void)getMainNewsIndexPathWithNotify:(NSNotification *)notify {

    NSIndexPath *indexPath = notify.object;
    
    [self reloadData];
    
    [self selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    
    [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];

}

/// 注销通知
- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

#pragma mark - 使用NSUrlConnection加载网络数据
- (void)loadServiceDataWithUrlString:(NSString *)urlStr completionBlock:(void (^)())completionBlock{
    
    NSURL *url = [NSURL URLWithString:urlStr];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        
        // 调试代码 看看所需要的数据data
//        NSLog(@"data:%@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
        
        NSArray *dataArr = dict[@"tList"];
        
        [dataArr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSDictionary *dict = obj;
            
            ZZNewsChannelModel *newsChannelModel = [ZZNewsChannelModel newsChannelModelWithDict:dict];
            
            [self.channels addObject:newsChannelModel];
            
        }];
        
        // 刷新数据
        [self reloadData];
        
        if (completionBlock) {
            
            completionBlock();
            
        }
        
    }];
    
}

#pragma mark - UICollectionViewDelegateFlowLayout 
///动态改变itemSize的方法 然后flowLayout.itemSize的值就失效了
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    ZZNewsChannelModel *channelModel = self.channels[indexPath.item];
    
    return [self getItemSizeWithTname:channelModel.tname];

}

/// 计算选中之后的Label的大小
- (CGSize)getItemSizeWithTname:(NSString *)tname {

    UILabel *label = [[UILabel alloc] init];
    
    label.text = tname;
    
    label.font = [UIFont systemFontOfSize:18];
    
    [label sizeToFit];
    
    return label.bounds.size;

}

#pragma mark - UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return self.channels.count;

}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    ZZNewsChannelCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:KZZNewsChannelCell forIndexPath:indexPath];
    
    ZZNewsChannelModel *newsChannelModel = self.channels[indexPath.item];
    
    cell.channelModel = newsChannelModel;
    
    return cell;
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    ZZNewsChannelCollectionViewCell *cell = (ZZNewsChannelCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];

    ZZNewsChannelModel *channelModel = self.channels[indexPath.item];
    
    [self scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
    
    cell.channelModel = channelModel;
    
    //MARK:发送通知，通知新闻主界面，新闻频道栏的滚动点击位置
    [[NSNotificationCenter defaultCenter] postNotificationName:@"NewsChannelIndexPath" object:indexPath];

}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

    ZZNewsChannelCollectionViewCell *cell = (ZZNewsChannelCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    ZZNewsChannelModel *channelModel = self.channels[indexPath.item];
    
    cell.channelModel = channelModel;

}

#pragma mark - 懒加载
- (NSMutableArray *)channels {

    if (!_channels) {
        
        _channels = [NSMutableArray array];
        
    }
    
    return _channels;
}
@end
